/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type FormData = {
  curves: pickedLineData[];
  tol: number;
};

type Params = {
  curves: string[];
  tol: number;
};

// 曲线接合
function CommandCurveJoin({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    curves: [],
    tol: 0.1,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const params: Params = props.params;
    const { curves, tol } = params;
    await initEditDependency(curves);

    setFormData({
      curves: curves.map(
        (curve) => picker.generatePickObjByPickID(curve) as pickedLineData,
      ),
      tol: tol,
    });
  }, []);

  const isFormDataValid = () => {
    const { curves, tol } = formData;
    return curves.length > 1 && tol > 0;
  };

  const execute = async (preview = false) => {
    const { curves, tol } = formData;

    return confirmCommand(
      {
        type: 'Join',
        a: {
          curves: curves.map((i) => i.edgeId),
          tol,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    clear();
    if (!isFormDataValid()) {
      return;
    }
    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute();

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-curve-join', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curves: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickCurve,
        uniqueItems: true,
      },
      tol: {
        type: 'number',
        title: '误差',
        default: 0.1,
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curves: {
          'ui:placeholder': '请输入接合曲线',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      noValidate
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveJoin: CurvedBaseCommand = {
  id: 'CommandCurveJoin',
  label: 'command.curve-join',
  icon: 'commands/curved/curve-join',
  create: (label, onClose, props) => (
    <CommandCurveJoin
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
